﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.IO;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Drawing;
using System.Drawing.Imaging;
using System.Xml.Linq;
using System.Threading;
using System.Web.Services.Protocols;
using System.Net;

namespace Nivdal.Sponsors
{
    public partial class SponsorPreferences : System.Web.UI.Page
    {
        public string ServerfileName = "";
        private string SponsorsloadDirectory;
        private string SponsorsTemploadDirectory;
        protected void Page_Load(object sender, EventArgs e)
        {
            SponsorsloadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "Sponsors\\SponsersLogo");
            SponsorsTemploadDirectory = Path.Combine(
               Request.PhysicalApplicationPath, "Sponsors\\SponsersTempLogo");
            if (!IsPostBack)
            {
                this.NewSponsorGetDetailsSqlDataSource.SelectParameters.Add("SponsorId", Session["SponsorId"].ToString());
                //this.MessageLabel.Text = Session["SponsorId"].ToString();
            }


        }

        public bool CheckImgFile(string FileExtantion)
        {

            if (FileExtantion.Equals(".jpg") || (FileExtantion.Equals(".gif")) || (FileExtantion.Equals(".bmp")) || (FileExtantion.Equals(".png")))
                return true;
            else
                return false;
        }

        public System.Drawing.Bitmap ResizeImgFile(System.Drawing.Bitmap img, int width, int height)
        {

            System.Drawing.Bitmap ResizedImg = ResizeImage(img, width, height, ResizeOptions.MaxWidthAndHeight);
            return ResizedImg;

        }

        protected string UploadBanner(bool ToShow)
        {
            string ServerfileName = "";
            this.MessageLabel.Text = "";
            FileUpload bfu = SponsorPreferencesFormView.FindControl("BannerFileUpload") as FileUpload;
            System.Web.UI.WebControls.Image NormalImage = SponsorPreferencesFormView.FindControl("NormalImage") as System.Web.UI.WebControls.Image;
            string num = DateTime.Now.Year.ToString() + DateTime.Now.DayOfYear.ToString() +
            DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() +
            DateTime.Now.Second.ToString() + DateTime.Now.Millisecond.ToString();
            int intFileSizeLimit = 2048;
            string extension = Path.GetExtension(bfu.PostedFile.FileName);
            string filenameNoExtension = Path.GetFileNameWithoutExtension(bfu.PostedFile.FileName);
            ServerfileName = num + extension;
            string FullUploadPath = Path.Combine(SponsorsTemploadDirectory, ServerfileName);
            string FileExtantion = (Path.GetExtension(bfu.FileName).ToLower());
            if (CheckImgFile(FileExtantion) && bfu.PostedFile.ContentLength / 1024 < intFileSizeLimit)
            {
                System.Drawing.Bitmap ResizedBanner = ResizeImgFile(new System.Drawing.Bitmap(bfu.PostedFile.InputStream), 150, 150);
                try
                {
                    //ResizedTeamLogo.SetResolution(150,150);
                    ResizedBanner.SetResolution(150, 150);
                    ResizedBanner.Save(FullUploadPath);
                    if (ToShow)
                    {
                        NormalImage.Visible = true;
                        NormalImage.ImageUrl = "~/Sponsors/SponsersTempLogo/" + ServerfileName;
                        this.IsImageChecked.Value = "true";
                    }

                }
                catch (Exception err)
                {
                    this.MessageLabel.Text = err.Message + FullUploadPath + ServerfileName;

                }
            }

            else
            {
                MessageLabel.Text = Resources.Resource.Preferences_LeftImageFileError + " " + intFileSizeLimit + Resources.Resource.Preferences_RightImageFileError + " ";
                //return "Error";

            }

            return "~/Sponsors/SponsersTempLogo/" + ServerfileName;

        }
        public enum ResizeOptions
        {
            // Use fixed width & height without keeping the proportions
            ExactWidthAndHeight,

            // Use maximum width (as defined) and keeping the proportions
            MaxWidth,

            // Use maximum height (as defined) and keeping the proportions
            MaxHeight,

            // Use maximum width or height (the biggest) and keeping the proportions
            MaxWidthAndHeight
        }

        public static System.Drawing.Bitmap DoResize(System.Drawing.Bitmap originalImg, int widthInPixels, int heightInPixels)
        {
            System.Drawing.Bitmap bitmap;
            try
            {
                bitmap = new System.Drawing.Bitmap(widthInPixels, heightInPixels);
                using (System.Drawing.Graphics graphic = System.Drawing.Graphics.FromImage(bitmap))
                {
                    // Quality properties
                    graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                    graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
                    graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;
                    graphic.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;

                    graphic.DrawImage(originalImg, 0, 0, widthInPixels, heightInPixels);
                    return bitmap;
                }
            }
            finally
            {
                if (originalImg != null)
                {
                    originalImg.Dispose();
                }
            }
        }

        public static System.Drawing.Bitmap ResizeImage(System.Drawing.Bitmap image, int width, int height, ResizeOptions resizeOptions)
        {
            float f_width;
            float f_height;
            float dim;
            switch (resizeOptions)
            {
                case ResizeOptions.ExactWidthAndHeight:
                    return DoResize(image, width, height);

                case ResizeOptions.MaxHeight:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    width = (int)((float)(height) * dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidth:
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;
                    height = (int)((float)(width) / dim);
                    return DoResize(image, width, height);

                case ResizeOptions.MaxWidthAndHeight:
                    int tmpHeight = height;
                    int tmpWidth = width;
                    f_width = image.Width;
                    f_height = image.Height;

                    if (f_width <= width && f_height <= height)
                        return DoResize(image, (int)f_width, (int)f_height);

                    dim = f_width / f_height;

                    // Check if the width is ok
                    if (f_width < width)
                        width = (int)f_width;
                    height = (int)((float)(width) / dim);
                    // The width is too width
                    if (height > tmpHeight)
                    {
                        if (f_height < tmpHeight)
                            height = (int)f_height;
                        else
                            height = tmpHeight;
                        width = (int)((float)(height) * dim);
                    }
                    return DoResize(image, width, height);
                default:
                    return image;
            }
        }

        void LinkButton_Command(Object sender, CommandEventArgs e)
        {
            MessageLabel.Text = "You chose: " + e.CommandName + " Item " + e.CommandArgument;
        }

        protected void SubmitButton_Click(object sender, EventArgs e)
        {
            MessageLabel.Text = "false";
            //string AddSponsorResult = "";
            System.Web.UI.WebControls.Image NormalImage = SponsorPreferencesFormView.FindControl("NormalImage") as System.Web.UI.WebControls.Image;
            FileUpload bfu = SponsorPreferencesFormView.FindControl("BannerFileUpload") as FileUpload;
            TextBox NameTextBox = SponsorPreferencesFormView.FindControl("NameTextBox") as TextBox;
            TextBox LinkTextBox = SponsorPreferencesFormView.FindControl("LinkTextBox") as TextBox;
            HiddenField CreditUsageMultiplierHiddenField = SponsorPreferencesFormView.FindControl("CreditUsageMultiplierHiddenField") as HiddenField;
            TextBox EmailTextBox = SponsorPreferencesFormView.FindControl("emailTextBox") as TextBox;
            TextBox TeamsLimitTextBox = SponsorPreferencesFormView.FindControl("TeamsLimitTextBox") as TextBox;



            //if (NormalImage.Visible == false && (!(BannerFileUpload.HasFile && BannerFileUpload.PostedFile != null))) //user did not check banner and  uploaded a new one
            // if (this.IsImageChecked.Value == "false" && (!(BannerFileUpload.HasFile && BannerFileUpload.PostedFile != null))) //user did not check banner and  uploaded a new one
            //this.NoBannerDivAlert.InnerHtml = "<span style=color:Red;'>*</span>";
            if (NormalImage.Visible == true) //Advertise uploaded and checked the banner
            {
                ServerfileName = NormalImage.ImageUrl;
                //Response.Write(" ServerfileName: " + ServerfileName);

            }


            else if (bfu.HasFile && bfu.PostedFile != null) //Advertise Uploaded the banner but did not check it
            {
                ServerfileName = UploadBanner(false);
                //Response.Write(" false: ServerfileName: " + ServerfileName);

            }
            if (ServerfileName == "") //user did not upload a new image
            {
                HiddenField OldBannerURLHiddenField = SponsorPreferencesFormView.FindControl("OldBannerURLHiddenField") as HiddenField;
                ServerfileName = OldBannerURLHiddenField.Value.ToString();

            }
           
            string SponsorName = NameTextBox.Text.Trim();
            string Link = LinkTextBox.Text.Trim();
            string CreditUsageMultiplier = CreditUsageMultiplierHiddenField.Value;
            string Email = EmailTextBox.Text.Trim();
            string TeamsLimit = TeamsLimitTextBox.Text.Trim();
            

            string conn = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            System.Data.IDbConnection dbConnection = new System.Data.SqlClient.SqlConnection(conn);
            System.Data.IDbCommand dbCommand = new System.Data.SqlClient.SqlCommand();
            dbCommand.CommandText = "Nivdal_NewSponsorUpdateDetails";
            dbCommand.CommandType = CommandType.StoredProcedure;
            dbCommand.Connection = dbConnection;


            SqlParameter dbParam_SponsorId = new SqlParameter();
            dbParam_SponsorId.ParameterName = "@SponsorId";
            dbParam_SponsorId.Value = Session["SponsorId"].ToString();
            dbParam_SponsorId.DbType = DbType.String;
            dbParam_SponsorId.Size = 64;
            dbCommand.Parameters.Add(dbParam_SponsorId);

            SqlParameter dbParam_SponsorName = new SqlParameter();
            dbParam_SponsorName.ParameterName = "@Name";
            dbParam_SponsorName.Value = SponsorName;
            dbParam_SponsorName.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_SponsorName);

            SqlParameter dbParam_Email = new SqlParameter();
            dbParam_Email.ParameterName = "@Email";
            dbParam_Email.Value = Email;
            dbParam_Email.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_Email);

            SqlParameter dbParam_Banner = new SqlParameter();
            dbParam_Banner.ParameterName = "@Banner";
            dbParam_Banner.Value = ServerfileName;
            dbParam_Banner.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_Banner);

            SqlParameter dbParam_SponsorLink = new SqlParameter();
            dbParam_SponsorLink.ParameterName = "@Link";
            dbParam_SponsorLink.Value = Link;
            dbParam_SponsorLink.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_SponsorLink);

            SqlParameter dbParam_CreditUsageMultiplier = new SqlParameter();
            dbParam_CreditUsageMultiplier.ParameterName = "@CreditUsageMultiplier";
            dbParam_CreditUsageMultiplier.Value = CreditUsageMultiplier;
            dbParam_CreditUsageMultiplier.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_CreditUsageMultiplier);

            SqlParameter dbParam_TeamsLimit = new SqlParameter();
            dbParam_TeamsLimit.ParameterName = "@TeamsLimit";
            dbParam_TeamsLimit.Value = TeamsLimit;
            dbParam_TeamsLimit.DbType = DbType.String;
            dbCommand.Parameters.Add(dbParam_TeamsLimit);


            SqlParameter dbParam_Answer = new SqlParameter();
            dbParam_Answer.ParameterName = "@Answer";
            dbParam_Answer.Value = "";
            dbParam_Answer.DbType = DbType.String;
            dbParam_Answer.Direction = ParameterDirection.Output;
            dbParam_Answer.Size = 64;
            dbCommand.Parameters.Add(dbParam_Answer);

            try
            {

                dbConnection.Open();
                dbCommand.ExecuteScalar();
                string Answer = dbParam_Answer.Value.ToString();
                this.MessageLabel.Text = Answer;
            }
            catch (Exception SQLDBException)
            {
                this.MessageLabel.Text = Convert.ToString(SQLDBException);
                return;

            }

            finally
            {
                dbConnection.Close();
            }
        }



        protected void Upload_Click(object sender, EventArgs e)
        {
            FileUpload bfu = SponsorPreferencesFormView.FindControl("BannerFileUpload") as FileUpload;
            if (bfu.HasFile)
            {
                //this.MessageLabel.Text = "true";
                ServerfileName = UploadBanner(true);
                //this.IsBannerExist.Value = "true";

            }
        }

    }
}
